package com.grep.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.grep.base.util.PinYin4jUtil;
import com.grep.base.util.UUIDGenerator;
import com.grep.extra.dao.impl.TaskDAOSQL;
import com.grep.extra.dao.impl.WebSiteDAOSQL;
import com.grep.web.tool.GrepTest;
import com.grep.web.tool.Target;

/**
 * Servlet implementation class NewSiteTask
 */
public class GrepTestServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		
		String url = request.getParameter("testurl");
		String content = request.getParameter("testcontents"); 
		JSONObject jb = JSONObject.fromObject(content);
		JSONArray array = jb.getJSONArray("targets");
		int size = array.size();
		List<Target> targets = new ArrayList<Target>();
		for(int i=0;i<size; i++){
			String targetString = array.getString(i);
			JSONObject target = JSONObject.fromObject(targetString); 
			String targetName = target.getString("targetname");
			String targetBegin = target.getString("targetbegin");
			String targetEnd = target.getString("targetend");
			System.out.println(targetName+":"+targetBegin+"+"+targetEnd);
			Target t = new Target(targetName,targetBegin,targetEnd);
			targets.add(t);
		}
		Map<String,String> map = GrepTest.getRegexContent(url, targets);
		RequestDispatcher rd = this.getServletContext().getRequestDispatcher("/tool/grep_test.jsp");

		request.setAttribute("grepresult",map);
		request.setAttribute("testurl", url);
		request.setAttribute("targetMap", targets);
		rd.forward(request, response);
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

}
